import json

import requests  # 爬虫必备

def get_hot_comments(res):
    comments_json = json.loads(res.text)
    hot_comments = comments_json['data']['hotComments']
    with open('hot_comments.txt', 'w', encoding='utf-8') as file:
        for each in hot_comments:
            file.write(each['user']['nickname'] + ':\n\n')
            file.write(each['content'] + '\n')

def get_comments(url):
    headers = {
        'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0', 'Referer': "https://music.163.com/song?id"
                                                                                 "=416388799"}
    params = ("eu8BvYKxasfA7J8CjLrGR6Dd23X0CUGVtt/lcJmH2rO9e9N+ELYn876tcaU9yqQZSG"
              "+HmOGGdXnMoZWeHOo7KKMcEeoDxrkHuGHCSiCgGfAKDXcB6JsuF5ZbPWy/pAYeJZ4J1NRG0/aZ//Jv55ZPeuSOejdK3v"
              "+dHvRFphS6gweM7h9nEGESdEdGA5WBhk6h4BIRF6N4vYi8Jl3ZEX+ix2b8askNRIcYUdZlM8WVrsBSu0U3aZ"
              "+9lYlNPt6Su8vANroXXKH44Kt5VTMqXat2uIFdKip2Y/wXzU7gECdtXMJCQwm"
              "/2HA8XSUfp2kmwuaSaYER9sA5f6rWm82KAEP0HMxyLyuZ4zQ8WGF6NqSz4N4=")
    encSecKey = ("397e3b064d089d4b303ced1ae7e48fe5a44af0cc27fc151c7187a90ab899047a8f1c23b577cfa8260949c650ae2cfe8c"
                 "6388770f5028c0be048cd973f583d7212d56158f90f326754fed7ce1c81b9f664a056177ba1f11c6fd9843710e5b38"
                 "62c3a844ee661a7c560df566b3dd1d7b2d265f5cc3e7eee310ece84b31192b9d0f")
    data = {
        'params': params,
        'encSecKey': encSecKey
    }
    target_url = "https://music.163.com/weapi/comment/resource/comments/get?csrf_token=48909b0f7514f76d7c16b774f354bead"
    res = requests.post(target_url, headers=headers, data=data)

    return res


def main():
    url = input("请输入链接地址")
    res = get_comments(url)
    get_hot_comments(res)


if __name__ == "__main__":
    main()
